<script>
// 叠加分析
import { mapGetters } from 'vuex';
import mapManager from '../mapManager.js';
import * as utils from '@/utils/helps.js';

const reg = /[0-9a-z]/i;
const REFS = ['polygon', 'rectangle', 'marker', 'polyline', 'circle'];

export default {
  name: 'OverLapMap',
  props: {
    isAnalys: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      mapData: [],
      overlapMapId: '',
      num: 1,
    };
  },
  computed: {
    overlapClass() {
      return [!this.isAnalys ? 'splitscreen' : 'analysmap'];
    },
  },
  events: {
    'on-getmap': 'getMap',
  },
  watch: {
    isAnalys(newVal, oldVal) {
      if (newVal) {
        this.$nextTick(() => {
          const overLapLayer = this.totalMapData.filter(item => item.num === 3);
          if (this.$refs[overLapLayer[0].ref]) {
            mapManager.setMapLayer(overLapLayer[0].mapId, {
              ...overLapLayer[0],
              mapObj: this.$refs[overLapLayer[0].ref],
            });
            this.allMapObject.push(this.$refs[overLapLayer[0].ref].$mapObject);
            this.$emit('on-set-overlaplayer', true);
            this.singleMapEvent(this.$refs[overLapLayer[0].ref].$mapObject);
            window.dispatchEvent(new Event('resize'));
          }
        });
      }
    },
  },
  beforeMount() {
    this.setUuid();
    this.overlapMapId = `mapover${utils.randomWord(true, 3, 3)}`;
    // 三个地图的信息
    this.totalMapData = [];
    this.totalMapData = JSON.parse(JSON.stringify(this.mapData));
    this.totalMapData.push({
      ref: 'overLapMap3',
      mapId: this.overlapMapId,
      num: 3,
    });
    this.$emit('on-get-mapdata', this.totalMapData);
  },
  mounted() {
    this.$nextTick(() => {
      this.setMapObj();
      this._addMapEvents();
      // 添加事件
      this.$events.emit('on-getdraw-refs', { drawRefs: this.$refs, REFS });
    });
  },
  beforeDestroy() {
    this._removeMapEvents();
  },
  methods: {
    getMap() {
      this.$nextTick(() => {
        this.$events.emit('on-getdraw-refs', { drawRefs: this.$refs, REFS });
      });
    },
    setMapObj() {
      this.allMapObject = [];
      this.totalMapData.forEach(item => {
        if (this.$refs[item.ref]) {
          mapManager.setMapLayer(item.mapId, { ...item, mapObj: this.$refs[item.ref] });
          this.allMapObject.push(
            this.$refs[item.ref][0]
              ? this.$refs[item.ref][0].$mapObject
              : this.$refs[item.ref].$mapObject
          );
        }
      });
    },
    setUuid() {
      if (this.mapData.length < 2) {
        const mapid = utils.randomWord(true, 3, 3);
        if (reg.test(mapid)) {
          this.mapData.push({
            num: this.num,
            ref: `overLapMap${this.num}`,
            mapId: `mapover${mapid}`,
          });
          this.num++;
        }
        this.setUuid();
      }
    },
    // 给创建的所有map绑定事件
    _addMapEvents() {
      this.allMapObject.forEach(mapObject => {
        this.singleMapEvent(mapObject);
      });
    },
    singleMapEvent(mapObject) {
      mapObject.on('zoomend', this._zoomAllMap, this);
      mapObject.on(
        'focus',
        function() {
          mapObject.on('dragend', this._dragAllMap, this);
        },
        this
      );
      mapObject.on(
        'blur',
        function() {
          mapObject.off('dragend', this._dragAllMap, this);
        },
        this
      );
    },
    // 移除所有的map事件
    _removeMapEvents() {
      this.allMapObject.forEach(mapObject => {
        mapObject.off('zoomend', this._zoomAllMap, this);
        mapObject.off(
          'focus',
          function() {
            mapObject.off('dragend', this._dragAllMap, this);
          },
          this
        );
        mapObject.off(
          'blur',
          function() {
            mapObject.off('dragend', this._dragAllMap, this);
          },
          this
        );
      });
    },
    // 得到目标视图
    _getMapView(e) {
      let targetMap = e.target;
      let targetZoom = targetMap.getZoom();
      let targetCenter = targetMap.getCenter();
      return { targetMap, targetZoom, targetCenter };
    },
    _zoomAllMap(e) {
      const getMap = this._getMapView(e);
      this.allMapObject.map(mapObject => {
        if (mapObject !== getMap.targetMap) {
          if (mapObject._animateToZoom !== getMap.targetZoom) {
            mapObject.setView(getMap.targetCenter, getMap.targetZoom);
          }
        }
      });
    },
    _dragAllMap(e) {
      const getMap = this._getMapView(e);
      this.allMapObject.map(mapObject => {
        if (mapObject !== getMap.targetMap) {
          mapObject.setView(getMap.targetCenter, getMap.targetZoom);
        }
      });
    },
    drawGeometry(layers) {
      this.$events.emit('on-get-drawlayer', layers);
    },
  },
};
</script>

<template>
  <div
    :class="overlapClass"
    class="datav-overlapmap">
    <BaseMap
      v-for="(item,index) in mapData"
      :key="index"
      :ref="item.ref"
      :map-id="item.mapId"
    >
      <MousePosition></MousePosition>
      <NavControl></NavControl>
      <TileWMSLayer></TileWMSLayer>
      <GeoJson light-geometry></GeoJson>
      <TemporaryLayers></TemporaryLayers>
      <MapPolygon
        ref="polygon"
        @on-draw-polygon="drawGeometry"></MapPolygon>
      <MapRectangle
        ref="rectangle"
        @on-draw-rectangle="drawGeometry"></MapRectangle>
      <MapMarker
        ref="marker"
        @on-draw-marker="drawGeometry"></MapMarker>
      <MapPolyLine
        ref="polyline"
        @on-draw-polyline="drawGeometry"></MapPolyLine>
      <MapCircle
        ref="circle"
        @on-draw-circle="drawGeometry"></MapCircle>
    </BaseMap>
    <BaseMap
      v-if="isAnalys"
      ref="overLapMap3"
      :map-id="overlapMapId">
      <MousePosition></MousePosition>
      <NavControl></NavControl>
      <TileWMSLayer></TileWMSLayer>
      <GeoJson light-geometry></GeoJson>
      <TemporaryLayers></TemporaryLayers>
    </BaseMap>
  </div>
</template>

<style lang="less" scoped>
.datav-overlapmap {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  float: left;
}

.splitscreen {
  .k-map-container {
    float: left;
    width: 50%;
    height: 100%;
  }
  .k-map-container:first-child {
    border-right: 2px solid #495060;
  }
}

.analysmap {
  .k-map-container {
    float: left;
    width: 33.3%;
  }
  .k-map-container {
    border-right: 2px solid #495060;
  }
  .k-map-container:last-child {
    border-right: none;
  }
}
</style>
